# 蒙特卡洛树搜索模块
# Monte Carlo Tree Search
import copy

from src.go import Go
from ai.engine import Honinbo


class Mcts:
    def __init__(self):
        self.root = None
        self.engine = Honinbo()

    # 分析当前局面
    def analyze(self, goban: list):
        root_legal, root_probas, root_winner, root_string, root_board = self.engine.do_analyze(goban=goban)
        self.root = Node(string=root_string, board=root_board, legal_list=root_legal, probas=root_probas)
        # 合法落点共5个
        if len(goban) == 0:
            color = 1
        else:
            color = self.engine.go.reverse_color(goban[len(goban) - 1]['color'])
        print("上一步的合法落子点为 root_legal->", root_legal)
        # 把这步棋模拟的内容加上
        for i in range(len(root_legal)):
            single = root_legal[i]
            x = single['x']
            y = single['y']
            temp_goban = copy.deepcopy(goban)
            temp_goban.append({
                'x': x,
                'y': y,
                'color': color
            })
            color_text = self.engine.go.get_color_text_by_num(color)
            success, board, string, robX, robY = self.engine.go.go_logic(x, y, color_text)
            legal, probas, winner, analyze_string, analyze_board = self.engine.do_analyze(temp_goban)
            print("扩展的合法落子点 legal->", legal)
            self.root.expand(string=string, board=board, legal_list=legal, probas=probas)



    def mct_expand(self):
        pass


class Node:
    def __init__(self, string, board, legal_list, probas, parent=None):
        # 围棋数据
        self.string = string
        self.board = board
        self.legal_list = legal_list
        self.probas = probas
        # 树枝节点
        self.parent = parent
        # 子树集合
        self.leaf = []

        # 遍历的次数
        self.num = 0

    # 是否是树叶
    def is_leaf(self):
        return len(self.leaf) == 0

    def expand(self, string, board, legal_list, probas):
        # 这里父节点就是自己
        self.leaf.append(Node(string=string, board=board, legal_list=legal_list, probas=probas, parent=self))

    def get_leaf(self):
        return self.leaf
